package com.example.starter.work1

import io.vertx.core.AbstractVerticle
import io.vertx.core.Promise
import io.vertx.core.Vertx
import io.vertx.ext.web.Router
import io.vertx.kotlin.core.json.json
import io.vertx.kotlin.core.json.obj


class MainVerticle : AbstractVerticle() {
  private val threadLocal = ThreadLocal<Long>()
  override fun start(startPromise: Promise<Void>) {
    val router = Router.router(vertx);
    var list:List<Student> = listOf()
    val mMutableList = list.toMutableList()
    router.get("/api/add/:name/:no/:chinese").handler { ctx ->
      val name = ctx.request().getParam("name")
      val no = ctx.request().getParam("no")
      val chinese = ctx.request().getParam("chinese")
      val student: Student = Student()
      student.name=name;
      student.no=no.toInt();
      student.chinese=chinese.toInt()
      mMutableList.add(no.toInt(),student)
      ctx.json(
        json {
          obj(
            "msg" to "成功"
          )
        }
      )
    }
    router.get("/api/average").handler { ctx ->

      var allChinese=0;
      mMutableList.forEach { student -> allChinese+=student.chinese }
      val average = allChinese/mMutableList.size;
      ctx.json(
        json {
          obj(
            "msg" to "成功",
            "chinese" to average
          )
        }
      )
    }
    router.get("/api/get/:no").handler { ctx ->
      val no = ctx.request().getParam("no")
      var s: Student = Student()
      mMutableList.forEach { student -> if (student.no==no.toInt()){
        s=student
      } }
      ctx.json(
        json {
          obj(
            "msg" to "成功",
            "name" to s.name,
            "no" to s.no,
            "chinese" to s.chinese,
          )
        }
      )
    }
    vertx
      .createHttpServer()
      .requestHandler(router)
      .listen(8888)
      .onSuccess{ server ->
        println("Server is running on port: ${server.actualPort()}")
      }

  }

  companion object {
    @JvmStatic
    fun main(args: Array<String>) {
      var vertx = Vertx.vertx()
      vertx.deployVerticle(MainVerticle())
    }
  }
}
class Student{
     lateinit var name:String ;
      var no:Int = 0;
      var chinese:Int = 0;
}

